package cn.caplike.demo.spring.security.dynamic.authorization.util;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;

/**
 * <b>日期工具类</b>
 *
 * <dl>
 *     <dt><b>ChangeLog:</b></dt>
 *     <dd>1.0.0@2020-04-27 11:18 - The Very First Version.</dd>
 *     <dd>1.0.1@2020-05-14 10:04 - 新增 {@link TimeUtils#format(String, LocalDateTime)}.</dd>
 *     <dd>1.0.2@2020-05-14 11:26 - 新增 {@link TimeUtils#fromTimestamp(long)} 和 {@link TimeUtils#fromDate(Date)}.</dd>
 * </dl>
 *
 * @author LiKe
 * @version 1.0.2
 * @date 2020-04-27 11:18
 */
@SuppressWarnings("unused")
public final class TimeUtils {

    private TimeUtils() {
    }

    /**
     * Description: 获取当前时间的日期对象
     *
     * @return java.util.Date
     * @author LiKe
     * @date 2020-04-27 11:24:44
     */
    public static Date now() {
        return Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * Description: 格式化日期
     *
     * @param pattern       日期格式, 形如 {@code yyyy-MM-dd HH:mm:ss}
     * @param localDateTime {@link LocalDateTime}, 如果传入 {@code null}, 则取 {@code LocalDateTime.now()}
     * @return java.lang.String 格式化后的日期字符串
     * @author LiKe
     * @date 2020-05-08 10:19:45
     */
    public static String format(String pattern, LocalDateTime localDateTime) {
        return Optional.ofNullable(localDateTime).orElse(LocalDateTime.now()).format(DateTimeFormatter.ofPattern(pattern, Locale.CHINA));
    }

    /**
     * Description: 时间戳转 {@link LocalDateTime}<br>
     * Ref: http://www.chinaoc.com.cn/p/1181907.html
     *
     * @param timestamp 时间戳
     * @return java.time.LocalDateTime 当前时区的 {@link LocalDateTime}
     * @author LiKe
     * @date 2020-05-14 10:23:33
     */
    public static LocalDateTime fromTimestamp(long timestamp) {
        return LocalDateTime.ofEpochSecond(timestamp / 1000, 0, OffsetDateTime.now().getOffset());
    }

    /**
     * Description: {@link Date} to {@link LocalDateTime}
     *
     * @param date {@link Date}
     * @return java.time.LocalDateTime
     * @author LiKe
     * @date 2020-05-14 11:25:19
     */
    public static LocalDateTime fromDate(Date date) {
        return Objects.requireNonNull(date, "Parameter date cannot be null.").toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}
